package com.hundsun.cprs.yyt.gateway.service.trade.impl;

import org.apache.commons.lang.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.enums.EnumCommonCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.gateway.request.AccountQuotaLogQueryRequest;
import com.hundsun.cprs.yyt.gateway.response.AccountQuotaLogListResponse;
import com.hundsun.cprs.yyt.gateway.response.AccountQuotaResponse;
import com.hundsun.cprs.yyt.gateway.response.BaseResponse;
import com.hundsun.cprs.yyt.gateway.response.UserEarnedSumResponse;
import com.hundsun.cprs.yyt.gateway.service.BaseService;
import com.hundsun.cprs.yyt.gateway.service.trade.AccountCommonService;
import com.hundsun.cprs.yyt.gateway.vo.AccountQuotaLogVo;
import com.hundsun.cprs.yyt.gateway.vo.AccountQuotaRequest;
import com.hundsun.cprs.yyt.service.account.domain.Account;
import com.hundsun.cprs.yyt.service.account.domain.AccountStat;
import com.hundsun.cprs.yyt.service.account.domain.query.AccountQuotaLogQuery;
import com.hundsun.cprs.yyt.service.account.service.AccountQuotaLogService;
import com.hundsun.cprs.yyt.service.account.service.AccountService;
import com.hundsun.cprs.yyt.service.account.service.AccountStatService;
import com.hundsun.cprs.yyt.service.quota.domain.Quota;
import com.hundsun.cprs.yyt.service.quota.domain.QuotaHold;
import com.hundsun.cprs.yyt.service.quota.service.QuotaHoldService;
import com.hundsun.cprs.yyt.service.quota.service.QuotaService;
import com.hundsun.cprs.yyt.util.BeanUtils;
import com.hundsun.cprs.yyt.util.DateUtil;

@Service
public class AccountCommonServiceImpl extends BaseService implements AccountCommonService {

    @Autowired
    private AccountService accountService;
    
    @Autowired
    private AccountQuotaLogService quotaLogService;

    @Autowired
    private AccountStatService accountStatService;
    
    @Autowired
    private QuotaService quotaService;
    
    @Autowired
    private QuotaHoldService quotaHoldService;

    @Override
    public AccountQuotaResponse getAccountQuota(AccountQuotaRequest request) {
        AccountQuotaResponse response = new AccountQuotaResponse();
        try {
        	Validate.notNull(request,"参数必填");
        	Validate.notNull(request.getUserId(),"会员信息必填");
        	
        	Quota quota = null;
        	if (request.getQuotaId() == null) {
        		quota = quotaService.getDefaultQuota();
			} else {
				quota = quotaService.selectQuoteById(request.getQuotaId());
			}
        	
        	response.setCurrentQuota(0l);
        	if (quota != null || request.getUserId() == null) {
				QuotaHold quotaHold = quotaHoldService.getQuoteHoldByUserAndQuoteId(request.getUserId(), quota.getId());
				if (quotaHold != null) {
					response.setCurrentQuota(quotaHold.getCanUseAmount());
				}
			}
            
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getErrorDesc());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public AccountQuotaLogListResponse selectAccountQuotaLog(AccountQuotaLogQueryRequest request) {
        AccountQuotaLogListResponse response = new AccountQuotaLogListResponse();
        try {
            Validate.notNull(request,"参数非法");
            Validate.notNull(request.getUserId(),"会员信息必填");
            
            AccountQuotaLogQuery query = BeanUtils.transfrom(AccountQuotaLogQuery.class, request);
            if(request.getStartDate() != null) {
            	query.setStartDate(DateUtil.strToDate(request.getStartDate(),"yyyy-MM-dd HH:mm:ss"));
            }
            if(request.getEndDate() != null) {
            	query.setEndDate(DateUtil.strToDate(request.getEndDate(),"yyyy-MM-dd HH:mm:ss"));
            }
            quotaLogService.selectByPage(query);
            
            if (query.getTotalCount() > 0) {
                response.setTotalCount(query.getTotalCount());
                response.setResult(BeanUtils.batchTransform(AccountQuotaLogVo.class, query.getData()));
            }
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getErrorDesc());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public BaseResponse exchangePoints(Long userId, Long quotaAmount) {
        BaseResponse response = new BaseResponse();
        try {
            Validate.notNull(userId,"参数非法");
            Validate.notNull(quotaAmount,"兑换配额数必填");
            //先校验用户的配额是否充足
            Account account = accountService.getAccountByUserId(userId);
            if (account == null){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1400.getErrorNo(),EnumBusinessCode.BUSINESS_1400.getErrorInfo());
            }
            //TODO:使用默认通用配额
            Quota quota = quotaService.getDefaultQuota();
            if (quota != null) {
				QuotaHold quotaHold = quotaHoldService.getQuoteHoldByUserAndQuoteId(userId, quota.getId());
				if (quotaHold == null || quotaHold.getCanUseAmount().compareTo(quotaAmount) < 0) {
					throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1401.getErrorNo(),EnumBusinessCode.BUSINESS_1401.getErrorInfo());
				}
			}
            //调用配额兑换积分的接口
            accountService.exchangePoints(userId,quotaAmount,quota);

        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getErrorDesc());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public UserEarnedSumResponse queryUserEarnedSum(Long userId) {
        UserEarnedSumResponse response = new UserEarnedSumResponse();
        try {
            Validate.notNull(userId,"用户信息必填");
            AccountStat accountStat = accountStatService.selectAccountStat(userId);
            if (accountStat != null){
                response.setEarnedSum(accountStat.getEarnedSum());
            }
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getErrorDesc());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }
}
